package com.threadlocal;

/**
 * 一个线程在不同的执行阶段需要用到同一份数据，又想避免层层传递参数的麻烦
 *
 * @author lemonwan
 */
public class ThreadLocalDemoTwo {
    public static void main(String[] args) {
        new ServiceOne().process();
    }
}

class User {
    String name;

    public User(String name) {
        this.name = name;
    }
}

class ServiceOne {
    public void process() {
        User user = new User("lemonwan");
        ThreadLocalHolder.holder.set(user);
        new ServiceTwo().process();
    }
}

class ServiceTwo {
    public void process() {
        User user = ThreadLocalHolder.holder.get();
        System.out.println("ServiceTwo : " + user.name);
        new ServiceThree().process();
    }
}

class ServiceThree {
    public void process() {
        User user = ThreadLocalHolder.holder.get();
        System.out.println("ServiceThree : " + user.name);
        ThreadLocalHolder.holder.remove();
    }
}

class ThreadLocalHolder {
    public static ThreadLocal<User> holder = new ThreadLocal<>();
}
